package com.ruoyi.framework.weixin;

import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.properties.WxProperties;
import com.ruoyi.framework.utils.JSONUtil;
import com.ruoyi.framework.utils.MyX509TrustManager;
import com.ruoyi.framework.utils.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.rmi.ConnectException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class WeixinApi {
    protected static Log log = LogFactory.getLog(WeixinApi.class);

    @Autowired
    WxProperties wxProperties;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取access_token
     * @return
     */
    public String getAccessToken(boolean flag){
        String key = "GET_ACCESS_TOKEN_" + wxProperties.getAppId();
        log.info("===appId：" + wxProperties.getAppId() + "===key：" + key);
        String accessToken = StringUtil.getTrim(redisTemplate.opsForValue().get(key));
        log.info("===get redis accessToken：" + accessToken);
        if (accessToken.isEmpty() || flag) {
            String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=" + wxProperties.getAppId() + "&secret=" + wxProperties.getAppSecrect() + "&grant_type=client_credential";
            String getTokenResponse = HttpUtils.sendGet(getTokenUrl);
            log.info("===get accessToken result：" + getTokenResponse);
            Map getTokenResult = JSONUtil.parseJSONToMap(getTokenResponse);
            accessToken = StringUtil.getTrim(getTokenResult.get("access_token"));
            redisTemplate.opsForValue().set(key, accessToken, 100, TimeUnit.MINUTES);
        }

        return accessToken;
    }

    public static boolean isValidToken(String token){
        Map<String,Object> map = JSONUtil.parseJSONToMap(token);
        String errCode = StringUtil.getTrim(map.get("errcode"));
        String errMsg = StringUtil.getTrim(map.get("errmsg"));
        if(errCode == null || errMsg == null)
            return true;
        if("0".equals(errCode) && "ok".equals(errMsg))
            return true;
        if("42001".equals(errCode) && errMsg.indexOf("access_token expired") >= 0)
            return false;

        if("40001".equals(errCode) && errMsg.indexOf("invalid credential") >= 0)
            return false;
        return true;
    }

    public Map postWechatAPI(String requestUrl,String params) {
        String result = this.httpsPost(requestUrl + this.getAccessToken(false), params);
        if (this.isValidToken(result) == false) {
            String newToken = this.getAccessToken(true);
            result = this.httpsPost(requestUrl + newToken, params);
        }
        return JSONUtil.parseJSONToMap(result);
    }


    public byte[] postWechatImage(String terminal, String requestUrl, String params) throws Exception {
        byte[] result = this.httpsPostStream(requestUrl + this.getAccessToken(false), params);

        return result;
    }

    public static String httpsPost(String requestUrl, String params) {
        String jsonstr = "{}";
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            String requestMethod = "POST";

            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != params) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(params.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonstr = buffer.toString();
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonstr;
    }

    public static byte[] httpsPostStream(String requestUrl, String params) throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(requestUrl);
        httpPost.addHeader("ContentTyp", "application/json");

        StringEntity stringEntity = new StringEntity(params, "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity(); // 响应结果
        byte[] data = readInputStream(entity.getContent());

        return data;
    }

    /**
     * description: 输入流转字节数组
     * create by: Mr.Fang
     *
     * @param inStream 输入流
     * @return: byte[]
     * @date: 2023/5/11 11:52
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }
}
